import time
import random
import pickle


import sys
import django
import os

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'djangoProject1.settings')
django.setup()

from web import models

def generate_tran(good, quan, optr, type, owner):
    models.Transaction.objects.create(
        Tran_ID=generate_tid(owner.id, optr.id, good.Good_ID, quan),
        good=good,
        quantity=quan,
        operator=optr,
        type=type,
        owner=owner
    )


def generate_tid(uid1, uid2, gid, q):
    # 获取当前时间戳，精确到秒
    timestamp = int(time.time())

    # 生成一个6位的随机数
    random_number = random.randint(100000, 999999)

    # 将时间戳和随机数拼接成字符串
    tid_string = f"{uid1}{timestamp}{uid2}{random_number}{q}{gid}"

    # 截取前32位作为GID
    tid = tid_string[:32]

    return tid


def buy(optr, good, quan):
    if not good:
        return False
    stock = good.stock
    if stock >= quan:
        generate_tran(good, quan, optr, 2, good.owner)
        stock -= quan
        good.buy += quan
        good.save()
        return True
    else:
        return False


def fill(good, quan):
    if not good:
        return False

    generate_tran(good, quan, good.owner, 1, good.owner)
    good.stock += quan
    good.save()
    return True

def view(good, q=1):
    if not good:
        return False

    good.views += q
    good.save()
    return True

def star(good, q=1):
    if not good:
        return False

    good.stars += q
    good.save()
    return True

def create_vusrs(num):
    usrs=[]
    for i in range(num):
        uid = ''.join(random.choice('0123456789') for _ in range(6))
        usr = models.UserInfo.objects.create(
            username='VUSR'+uid,
            password='VPASS'+uid,
            email=uid+'@vemail.com',
            mobile_phone='13246'+uid
        )
        usrs.append(usr)
    return usrs

def get_vusrlist():
    if os.path.exists('vusrdata'):
        with open('vusrdata', 'rb') as file:
            usrs = pickle.load(file)
        return usrs

    usrs = create_vusrs(10)
    with open('vusrdata', 'wb') as file:
        pickle.dump(usrs, file)

    return usrs

def run():
    vusrs = get_vusrlist()
    total_commodity = models.Good.objects.count()
    for i in range(200):
        index = random.randint(0, total_commodity - 1)
        good = models.Good.objects.all()[index]

        type = random.randint(1, 4)
        quan = random.randint(1, 3)

        index = random.randint(0, 9)
        vusr = vusrs[index]

        if type == 1:
            fill(good, quan*100)
        if type == 2:
            view(good)
            buy(vusr, good, quan)
        if type == 3:
            view(good, quan*3)
        if type == 4:
            view(good, quan * 3)
            star(good, quan*3)

if __name__ == '__main__':
    run()
